/**
 * @(#) ReqResupportMoneyMediator.as
 *
 * @date		2012. 09. 12.
 * @version		1.0
 * @author		Park, ju tae 
 * @description	휴양소 지원금 신청 - Mediator
 * 				휴양소 지원금을 신청하는 Presentation Logic을 관리
 */
package com.skt.common_hr.resupport.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.skt.common_hr.resupport.ResupportFacade;
	import com.skt.common_hr.resupport.events.ResupportMoneyEvent;
	import com.skt.common_hr.resupport.model.*;
	import com.skt.common_hr.resupport.model.vo.ResupportMoneyVO;
	import com.skt.common_hr.resupport.model.vo.ResupportSubTabVO;
	import com.skt.common_hr.resupport.view.components.ResupportView;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.NumberUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.formatters.DateFormatter;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class ReqResupportMediator extends CommonMediator
	{
		public static const NAME:String = "ResupportMoneyWriteMediator";
		public static const CLOSED_REQUEST_VIEW:String	= "closedRequestView";
		
 		private var bWaitingApproval:Boolean = false;
 		private var bWaitingExistData:Boolean = false;
		private var _currentKey:String = "";

		public var sGJAHR:String; //note.getBody().sGJAHR
		/**
		* 생성자
		*
		* @param
		* @return void
		*/
        public function ReqResupportMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			setEventListeners();
 		}

 		private function setEventListeners():void
 		{
 			// 신청창에서 리스트창으로
 			view.addEventListener(ResupportView.ResupportWriteClose, goMainList);
 			view.addEventListener(ResupportView.CLICK_SAVE, onSaveRequest);
 			view.addEventListener(ResupportFacade.APPROVAL_REQUEST, onApprovalRequest);
 		}

 		private function removeEventListener():void
 		{
 			// 신청창에서 리스트창으로
 			view.removeEventListener(ResupportView.ResupportWriteClose, goMainList);
 			view.addEventListener(ResupportView.CLICK_SAVE, onSaveRequest);
 			view.removeEventListener(ResupportFacade.APPROVAL_REQUEST, onApprovalRequest);
 		}

 		/**
		 * 입력으로 돌아가기
		 * @param
		 * @return void
		 */
 		private function goMainList(event:Event):void
 		{
 			clearView();
 			bActivated = false;
 			facade.sendNotification(CLOSED_REQUEST_VIEW, this);
 		}

 		override protected function clearView():void
 		{
 			trace("clear WriteMediator");
 		}

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		*
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return [
					ResupportFacade.LOAD_RESUPPORTMONEY_BANKA_COMPLETE,
					ResupportFacade.LOAD_RESUPPORTMONEY_WRITE_INITIAL,
					ResupportFacade.LOAD_MM_LIMIT_DATA_COMPLETE,
					ResupportFacade.LOAD_MM_LIMIT_DATA_FAILED,
					ResupportFacade.SAVE_RESUPPORTMONEY_COMPLETE,
					ResupportFacade.SAVE_RESUPPORTMONEY_FAILED,
					ResupportFacade.LOAD_RESUPPORTMONEY_DETAIL_COMPLETE,
					ResupportFacade.LOAD_RESUPPORTMONEY_DETAIL_FAILED,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE,
					ResupportFacade.LOAD_RESUPPORTMONEY_MEDSUBJECT_COMPLETE,
					ResupportFacade.LOAD_RESUPPORTMONEY_MEDSUBJECT_FAILED
					];
		}

		/**
		* Noti별로 처리한다.
		*
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName())
			{
				// 초기 로딩시..
				case ResupportFacade.LOAD_RESUPPORTMONEY_WRITE_INITIAL:
					bActivated = true;
					view.dataProvider.WSTATUS = "";
					view.currentState = "stateView";
					var t:Object = note.getBody();
					if(t.write == false) {
						view.bWrite = false;
					} else {
						view.bWrite = true;
					}
					sGJAHR = note.getBody().sGJAHR;
					loadInitialData(note.getBody().pernr, note.getBody().name, note.getBody().gwarekey);
					break;
				// 계좌정보
				case ResupportFacade.LOAD_RESUPPORTMONEY_BANKA_COMPLETE:
					setBankList(note.getBody() as AccountProxy);
					break;

//				case ResupportFacade.LOAD_MM_LIMIT_DATA_COMPLETE:
//					LitmitDateSetting(note.getBody() as ReqResupportWriteProxy);
//					break;
//				case ResupportFacade.LOAD_MM_LIMIT_DATA_FAILED:
//					trace("RESUPPORTMoneyFacade.LOAD_MM_LIMIT_DATA_FAILED");
//					break;
				case ResupportFacade.SAVE_RESUPPORTMONEY_COMPLETE:
					// 승인요청하여 결재창이 뜨도록.
					if(bWaitingApproval) {
						_currentKey = ResupportProxy(note.getBody()).key;
						view.dataProvider.GWAREKEY = parseInt(_currentKey);
						execApproval(_currentKey);

						completeRESUPPORTMoney(note.getBody());
					}
					else {
						completeRESUPPORTMoney(note.getBody());
						facade.sendNotification(CLOSED_REQUEST_VIEW, this);
					}
					if(view.sAlertInfo != '') {
						CommonAlert.showMessage(commonFacade.bundle, view.sAlertInfo, null);	
					}
					bWaitingApproval = false;
					break;

				case ResupportFacade.SAVE_RESUPPORTMONEY_FAILED:
					bWaitingApproval = false;
					CommonAlert.showMessage(commonFacade.bundle, ResupportProxy(note.getBody()).faultMessage, null);
					break;

				case ResupportFacade.LOAD_RESUPPORTMONEY_DETAIL_COMPLETE:
					if(bActivated) {
						setLoadedDetailInfo( ResupportProxy(note.getBody()) );
					}
					break;

				case ResupportFacade.LOAD_RESUPPORTMONEY_DETAIL_FAILED:
					trace("LoadCongmoneyWriteFailed");
					break;

				// 결재 요청  성공
				case RequestApprovalMediator.APPROVAL_COMPLETE:
					bActivated = false;
		 			clearView();
		 			facade.sendNotification(CLOSED_REQUEST_VIEW, this);
					break;

				// 결재 요청 취소
				case RequestApprovalMediator.APPROVAL_CANCEL:
					bActivated = true;
					break;
				
				default:
					break;
			}
		}

		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - 조회상세보기
		 * @param
		 * @return void
		 */
		
		private static var dateFormatter:DateFormatter = new DateFormatter();
		public static function toKorString(src:Date):String
		{
			dateFormatter.formatString = "YYYY년 MM월 DD일";
			return dateFormatter.format(src);
		} 
		 
 		private function setLoadedDetailInfo(voWrapObj:ResupportProxy):void
 		{
 			var vo:ResupportMoneyVO = voWrapObj.detailVO;
 			var ac:ArrayCollection = voWrapObj.subTabList;

			_currentKey = voWrapObj.detailVO.GWAREKEY.toString();

			view.lbTargetName.text = vo.ENAME;
			view.lbApplyDateYear.text = toKorString(vo.IDATE);
			view.lbApplyDateTxt.text = vo.WSTATX;
			view.lbTotalMoney.text = NumberUtil.NumberFormat(vo.BETRG_Y);
			view.lbApplyMoney.text = NumberUtil.NumberFormat(vo.BETRG_Q);
			view.lbRemainMoney.text = NumberUtil.NumberFormat(vo.BETRG);
			view.lbBank.text	= vo.BANKA;
			view.lbAccount.text	= vo.BANKN;
			view.lbBankName.text = vo.EMFTX;
			
			view.lbHOWMANEY.text = vo.HOWMANY.toString();
			view.lbHOWMUCH.text  = vo.HOWMUCH.toString();
			view.resupportData = ac;
 		}

		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - 계좌선택 콤보 load된 데이터를 화면에 출력
		 * @param
		 * @return void
		 */
 		private function setBankList(proxy:AccountProxy):void
 		{
 			view.accounts = proxy.AccountList;

 			if(bWaitingExistData) {

 			}
 			else {
 				//view.clearAccountInfo();
 			}
 			bWaitingExistData = false;
 		}

		/**
		 * RESUPPORTMoney 저장 완료한 후 호출됨
		 *
		 * @param
		 * @return void
		 */

 		private function completeRESUPPORTMoney(val:Object):void
 		{
 			_currentKey = val.key;
 		}

// 		private function LitmitDateSetting(proxy:ReqResupportWriteProxy):void
// 		{
// 			view.LitmitDateSetting(proxy.mmLimitDateLoadList);
//
// 			if(bWaitingExistData) {
//
// 			}
// 			else {
// 				//view.clearAccountInfo();
// 			}
// 			bWaitingExistData = false;
// 		}

		//최초
		private function loadInitialData(pernr:String, name:String, gwarekey:String=""):void
		{
			view.resupportData = new ArrayCollection();
			_currentKey = ""; // 현재 키 초기화
			
 			if(gwarekey!="") {
 				trace("modify data: " + gwarekey);
 				loadExistData(gwarekey);				//휴양소 지원금 신청(입력,업데이트) 				
 			}
 			else { 				
		 		loadBankInfo(Variables.myPernr);
 				loadRESUPPORTMoneyLimitData(Variables.myPernr, "" );	//휴양소 지원금 마감일자와 휴양소 지원금 지원가능금액 산출

 			}
		}

		private function onChgCbLoadRESUPPORTMoneyLimitData(e:Event):void {
			var sYear:String = view.lbApplyDateYear.text;

			loadRESUPPORTMoneyLimitData(Variables.myPernr, _currentKey);	//휴양소 지원금 마감일자와 휴양소 지원금 지원가능금액 산출
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Data Access Functions....
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////

		private function execApproval(key:String):void
		{
 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
 			if(approval==null) {
 				approval = new RequestApprovalMediator(view, "11");
 				facade.registerMediator(approval);
 			}
 			bActivated = false;
 			var appProxy:ResupportApprovalProxy = facade.retrieveProxy(ResupportApprovalProxy.NAME) as ResupportApprovalProxy;
 			appProxy.key = key;
 			appProxy.dataProvider = tmpVO;
 			approval.execRequest(view, appProxy);
		}



 		private function loadExistData(gwarekey:String):void
 		{
			var proxy:ResupportProxy = facade.retrieveProxy(ResupportProxy.NAME) as ResupportProxy;
			bWaitingExistData = true;
			proxy.loadDetail(gwarekey);
 		}

 		/**
		 * 휴양소 지원금 마감일자, 한도 조회
		 * @param
		 * @return void
		 */
 		private function loadRESUPPORTMoneyLimitData(pernr:String, gwarekey:String=""):void
 		{
			var proxy:ReqResupportWriteProxy = facade.retrieveProxy(ReqResupportWriteProxy.NAME) as ReqResupportWriteProxy;
			proxy.loadMmLimitData(pernr, gwarekey);
 		}

 		private function loadBankInfo(pernr:String):void
 		{
			var accountProxy:AccountProxy = facade.retrieveProxy(AccountProxy.NAME) as AccountProxy;
			accountProxy.loadAccounts(pernr);
 		}

 		private function onSaveRequest(event:Event):void
 		{
 			bWaitingApproval = false;
			commonSave();
 		}
 		
 		private function commonSave():void 
 		{
			var I_GWAREKEY:String 	= _currentKey;

			var tItabArr:Array = new Array();
			var oItab:Object = new Object;
			oItab.PERNR		= Variables.myPernr;
			oItab.GJAHR 	= sGJAHR;//'2012';

			tItabArr.push(oItab);  

			// SUB_TAB
 			var tSub_tabArr:Array = new Array();
	 		for each(var rec:ResupportSubTabVO in view.resupportData)
	 		{
	 			var data:Object = new Object;
	 			data.USEDT = DateUtil.toBasicString(rec.USEDT);
	 			data.BETRG = rec.BETRG;
	 			data.RUSE = rec.RUSE;
	 			data.RGBN = rec.RGBN;
	 			
	 			tSub_tabArr.push(data);
	 		}

 			var proxy:ResupportProxy = facade.retrieveProxy(ResupportProxy.NAME) as ResupportProxy;
 			proxy.save(I_GWAREKEY, tItabArr, tSub_tabArr);
 		}

 		// 승인 요청
		private var tmpVO:ResupportMoneyVO;
 		private function onApprovalRequest(event:ResupportMoneyEvent):void
 		{
 			bWaitingApproval = true;
 			//tmpVO = view.dataProvider;
 			tmpVO = event.writeVo;

 			commonSave();
 		}

        private function get view():ResupportView
        {
            return viewComponent as ResupportView;
        }


	}
}